package com.atom.common.activiti.log;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;

import com.atom.common.dao.HistoricTaskDao;
import com.atom.common.dao.LogUrlDao;
import com.atom.common.entity.LogUrlDO;
import com.atom.common.entity.bo.TaskLogBO;
import com.atom.common.exception.AvensFileException;
import com.atom.common.remote.file.RemoteFileCommand;
import com.atom.common.remote.file.RemoteFileDao;
import com.atom.common.util.CommonUserResolver;
import com.atom.common.util.JsonUtil;

@Component
public class LogHandler {

  @Resource HistoricTaskDao historicTaskDao;
  @Resource LogUrlDao urlDao;
  @Resource CommonUserResolver commonUserResolver;
  @Resource RemoteFileDao remoteFileDao;
  @Resource RemoteFileCommand command;

  public Map<String, Object> getData(String mainProcessInstanceId) {
    Map<String, Object> data = new HashMap<String, Object>();
    List<TaskLogBO> logs = historicTaskDao.findTaskLogList(mainProcessInstanceId);
    for (TaskLogBO log : logs) {
      log.setAssignee(commonUserResolver.getUserNameByUserId(log.getAssignee()));
    }
    data.put("data", JsonUtil.ObjectToJsonQuietly(logs));
    return data;
  }

  public File getHtml(String mainProcessInstanceId) {
    List<LogUrlDO> fileList = urlDao.findByProperty("mainProcessInstanceId", mainProcessInstanceId);
    if (fileList == null || fileList.size()!= 1) {
      throw new AvensFileException("Find file key by mainProcessInstanceId failed where mainProcessInstanceId = " + mainProcessInstanceId);
    }

    String url = fileList.get(0).getHtmlUrl();
    String filePath = command.downloadFile(url);
    File file = new File(filePath);
    if (file.exists()) {
      return file;
    }
    return null;
  }

  public boolean isHtml(String mainProcessInstanceId) {
    List<LogUrlDO> fileList = urlDao.findByProperty("mainProcessInstanceId", mainProcessInstanceId);
    if (fileList == null || fileList.size()== 0) {
      return false;    
    }
    return true;
  }

}
